package com.wuwei.elearning.question.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuwei.elearning.enumPackage.Constant;
import com.wuwei.elearning.question.domain.Subject;
import com.wuwei.elearning.question.domain.UserRecord;
import com.wuwei.elearning.question.mapper.SubjectMapper;
import com.wuwei.elearning.question.mapper.UserRecordMapper;
import com.wuwei.elearning.question.service.UserRecordService;
import com.wuwei.elearning.question.vo.EChartsBarVo;
import com.wuwei.elearning.utils.result.Result;
import com.wuwei.elearning.utils.token.TokenUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 用户做题记录表，每一个该表都对应一个用户做题记录 前端控制器
 * </p>
 *
 * @author wuwei
 * @since 2024-03-28
 */
@RestController
@RequestMapping("/elearning/userRecord")
@CrossOrigin
public class UserRecordController {


    @Resource
    private UserRecordService userRecordService;

    @Resource
    private UserRecordMapper userRecordMapper;
    @Autowired
    private SubjectMapper subjectMapper;


    /**
     * 当用户退出顺序练习界面时，会向数据库更新一下用户本次练习到了哪一道题
     * @param index 用户做到底几道题的索引
     * @param selectedId 如果小于10000，则为chapter表中的id字段，如果大于10000，则为subject表的id加上10000
     * @param request
     * @return
     */
    @PutMapping("updateOrAdd/{index}/{selectedId}/{rightNum}/{selectedNum}")
    public Result<String> addOrUpdate(@PathVariable("index") Integer index,@PathVariable("selectedId") Long selectedId,
                                      @PathVariable("rightNum") Integer rightNum,@PathVariable("selectedNum") Integer selectedNum,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        userRecordService.addOrUpdate(index,selectedId,account,rightNum,selectedNum);
        return Result.ok("更新成功!");
    }

    /**
     * 根据selectedId获取userRecord
     * @param selectedId 如果小于10000，则为chapter表中的id字段，如果大于10000，则为subject表的id加上10000
     * @param request
     * @return
     */
    @GetMapping("getBySelectId/{selectedId}")
    public Result<UserRecord> getByChapterId(@PathVariable("selectedId") Long selectedId, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        LambdaQueryWrapper<UserRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRecord::getSelectedId,selectedId).eq(UserRecord::getUserAccount,account);
        UserRecord userRecord = userRecordMapper.selectOne(queryWrapper);
        return Result.ok(userRecord);
    }

    /**
     * 删除用户做题的记录
     * 需要删除user_record表和select_record表
     * @param selectedId
     * @param request
     * @return
     */
    @DeleteMapping("deleteBySelectId/{selectedId}")
    public Result<String> deleteByChatperId(@PathVariable("selectedId") Long selectedId, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        userRecordService.deleteBySelectId(selectedId,account);
        return Result.ok("请从头来过！");
    }


    /**
     * 获取userRecord的统计数据
     * @return
     */
    @GetMapping("statistics/all")
    public Result<EChartsBarVo> statisticsAll( HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        return getEChartsBarVoResult(account, Arrays.asList(Constant.SUBJECTIDS));
    }

    @NotNull
    private Result<EChartsBarVo> getEChartsBarVoResult(Long account, List<Long> subjectIds) {
        LambdaQueryWrapper<UserRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(UserRecord::getSelectedId, subjectIds)
                .eq(UserRecord::getUserAccount, account);
        List<UserRecord> userRecords = userRecordMapper.selectList(queryWrapper);
        EChartsBarVo eChartsBarVo = new EChartsBarVo();
        List<String> xAxis = eChartsBarVo.getXAxis();
        List<String> data = eChartsBarVo.getData();
        List<Long> ids = eChartsBarVo.getIds();
        for (UserRecord userRecord : userRecords) {
            Integer selectedNum = userRecord.getSelectedNum();
            Integer rightNum = userRecord.getRightNum();
            Long subjectId = userRecord.getSelectedId();
            Subject subject = subjectMapper.selectById(subjectId);
            String name = subject.getName();
            double radio;
            if (selectedNum==0) {
                continue;
            } else {
                radio = (double) rightNum /selectedNum;
            }

            String formattedRadio = String.format("%.1f", radio*100);
            xAxis.add(name);
            data.add(formattedRadio);
            ids.add(subjectId);
        }
        return Result.ok(eChartsBarVo);
    }

    @GetMapping("statistics/{subjectId}")
    public Result<EChartsBarVo> statisticsSubjectId( HttpServletRequest request,@PathVariable("subjectId")Long subjectId){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        List<Long> subjectIds = subjectMapper.getLeafsIdByParentId(subjectId);
        return getEChartsBarVoResult(account,subjectIds);
    }
}

